﻿using MyHome.Server.PluginBase;
using System;
using System.Linq;
using System.Timers;

namespace TimerInputPlugin
{
    /// <summary>
    /// A plugin that will generate the current time every second.
    /// </summary>
    public class TimerInputPlugin : InputPlugin<object>
    {
        private Timer timer;

        public TimerInputPlugin()
        {
            Configuration.Add("Duration", "1000");
        }

        protected override void OnStart()
        {
            string sDuration;
            int duration;
            if(!(Configuration.TryGetValue("Duration", out sDuration) &&
                int.TryParse(sDuration, out duration)))
            {
                duration = 1000;
                Configuration["Duration"] = duration.ToString();
            }

            timer = new Timer(duration);
            timer.Elapsed += timer_Elapsed;
            timer.Start();
        }

        protected override void OnStop()
        {
            timer.Elapsed -= timer_Elapsed;
            timer.Dispose();
            timer = null;
        }

        private void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            OnNewValue(DateTime.Now.TimeOfDay.ToString());
        }
    }
}